// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
//商户配置
const mch_id = '1642611741' //商户号
//数据库服务
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID

  let functionName = 'refund_pay_callback' //结果通知回调云函数名:接收微信支付异步通知回调的云函数名
  let sub_mch_id = mch_id //微信支付分配的子商户号
  //let deviceInfo =   //终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB"
  let nonce_str = Math.random().toString(36).substr(2, 13) //随机字符串，不长于32位。推荐随机数生成算法
  let timeStamp = parseInt(Date.now() / 1000)
  let out_refund_no = 'TK_CHFS' + timeStamp + nonce_str //商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-
  //let feeType = 'CNY' //符合ISO 4217标准的三位字母代码，默认人民币：CNY
  let out_trade_no = event.outTradeNo
  let total_fee = event.totalFee
  let refund_fee = event.refundFee
  let refund_desc = event.refundDesc
  let detail = event.detail

  //前置检查：入参
  if (!out_trade_no || out_trade_no.trim().length == 0) {
    return {
      errCode: -1,
      errMsg: 'out_trade_no入参不能为空'
    }
  }
  //前置检查：查询当前订单状态
  const orderInfoList = await cloud.callFunction({
    name: 'db_Order',
    data: {
      type: 'queryOrderByOutTradeNo',
      outTradeNo: out_trade_no,
    }
  })
  if (!orderInfoList.data) {
    return {
      errCode: -1,
      errMsg: '查询订单数据不存在!'
    }
  }
  if (orderInfoList.data[0].status == 'PRODUCING') {
    return {
      errCode: -1,
      errMsg: '当前订单已进入待生产or生产中，无法退款，请联系商家处理!'
    }
  }
  if (orderInfoList.data[0].status == 'SHIPPED') {
    return {
      errCode: -1,
      errMsg: '当前订单已发货，无法退款，请联系商家处理!'
    }
  }
  //前置检查结束，处理退款
  const res = await cloud.cloudPay.refund({
    functionName,
    envId: 'ops-0gnuzw0q7bcf4c1a',
    sub_mch_id,
    nonce_str,
    out_trade_no,
    out_refund_no,
    total_fee,
    refund_fee,
    refund_desc
  })
  // if (res.returnCode != "SUCCESS") {
  //   return {
  //     errCode: -1,
  //     errCodeDes: "退款失败",
  //     errMsg: "退款失败",
  //     event
  //   }
  // }
  // if (res.resultCode != "SUCCESS") {
  //   return {
  //     errCode: -1,
  //     errCodeDes: res.errCodeDes,
  //     errMsg: "退款失败",
  //     event
  //   }
  // }
  if (res.returnCode != "SUCCESS") {
    return {
      errCode: res.returnCode,
      errMsg: res.returnMsg
    }
  }
  if (res.resultCode != "SUCCESS") {
    return {
      errCode: res.resultCode,
      errMsg: res.errCodeDes
    }
  }
  const nowTime = Date.now()
  let refundOrder = {
    _openid: openid,
    detail,
    subMchId: sub_mch_id,
    nonceStr: nonce_str,
    outTradeNo: out_trade_no,
    outRefundNo: out_refund_no,
    transactionId: res.transactionId,
    refundId: res.refundId,
    totalFee: total_fee,
    refundFee: refund_fee,
    refundDesc: refund_desc,
    refundStatus: 'PROCESSING',
    createTime: nowTime,
    modifyTime: nowTime
  }
  //db写入：退款订单表
  db.collection("refund_order").add({
    data: refundOrder
  });
  //const reqr = await cloud.cloudPay.queryRefund({
  //sub_mch_id,
  //nonce_str,
  // out_refund_no
  //})
  //if (reqr.resultCode == "SUCCESS") {
  //refundOrder.refund_status = reqr.refund_status_0 
  //}
  //再次向微信支付发起查询订单，查询成功后更新db订单信息
  cloud.callFunction({
    name: 'server_Order',
    data: {
      type: 'queryOrder',
      outTradeNo: out_trade_no,
    }
  })

  return {
    errCode: 0,
    errmsg: 'success',
    event,
    result: res
  }
}